package com.example.musicplayer.login

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.Toast
import com.example.musicplayer.R
import com.example.musicplayer.dao.UserProfileDAO
import com.example.musicplayer.model.UserProfile

class RegisterActivity : AppCompatActivity() {
    private lateinit var usernameEditText: EditText
    private lateinit var passwordEditText: EditText
    private lateinit var registerButton: Button
    private lateinit var progressBar: ProgressBar
    private lateinit var userProfileDAO: UserProfileDAO
    private lateinit var return_login: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)

        usernameEditText = findViewById(R.id.username)
        passwordEditText = findViewById(R.id.password)
        registerButton = findViewById(R.id.register)
        progressBar = findViewById(R.id.loading)
        userProfileDAO = UserProfileDAO(this)
        return_login = findViewById(R.id.return_login)

        registerButton.setOnClickListener {
            val username = usernameEditText.text.toString().trim()
            val password = passwordEditText.text.toString().trim()

            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(this, "Please enter both username and password", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            val userProfile = UserProfile(
                username = username,
                bio = "",
                phone = "",
                gender = "",
                birthday = "",
                location = "",
                school = "",
                image = null,
                password = password
            )

            progressBar.visibility = ProgressBar.VISIBLE
            val success = userProfileDAO.insertUserProfile(userProfile)
            progressBar.visibility = ProgressBar.GONE

            if (success) {
                Toast.makeText(this, "Registration successful", Toast.LENGTH_SHORT).show()
                val intent = Intent(this, LoginActivity::class.java)
                startActivity(intent)
                finish()
            } else {
                Toast.makeText(this, "Registration failed", Toast.LENGTH_SHORT).show()
            }
        }

        return_login.setOnClickListener {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
        }
    }
}